<?php
class Attendance extends BaseMongoDocument
{
    public $user_id;
    public $item_type_id;
    public $start_time;
    public $end_time;
    public $about;
    
    public $status = self::STATUS_PENDING;
    const STATUS_APPROVE = 'approve';
    const STATUS_PENDING = 'pending';
    
    public function getCollectionName()
    {
        return 'attendance';
    }
    
    /**
	 * Returns the static model of the specified AR class.
	 * @return User the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
    
    public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('item_type_id', 'required'),
            array('user_id', 'checkUser'),
            array('start_time', 'filterTime'),
            array('end_time', 'filterTime'),
            array('about, ctime, mtime, status', 'safe'),
		);
    }
    
    public function beforeValidate()
    {
        if(parent::beforeValidate())
        {
            return true;
        }
        else
            return false;
    }
    
    public function beforeSave()
    {
        if(parent::beforeSave())
        {
            return true;
        }
        else
            return false;
    }
    
    public function attributeLabels()
    {
        return array(
            '_id'=> 'ID',
            'item_type_id' => '项目类型',
            'start_time' => '开始时间',
            'end_time' => '结束时间',
            'about' => '备注',
            'ctime' => '创建时间',
            'mtime' => '修改时间',
        );
    }
    
    public function checkUser($attributeName, $params)
    {
        $attribute = $this->{$attributeName};
        if($this->getIsNewRecord() &&  empty($attribute))
        {
            $user = User::model()->getUser();
            if($user instanceof User)
                $this->{$attributeName} = $user->getId();
            else
            {
                $this->addError('user_id', 'user does not exist.');
                return false;
            }
        }
    }
    
    public function filterTime($attributeName, $params)
    {
        $attribute = $this->{$attributeName};
        if(empty($attribute))
        {
            $this->addError($attributeName, $attributeName.' cannot be blank.');
            return false;
        }

        if(is_string($attribute))
            $this->{$attributeName} = strtotime($attribute);
        elseif(is_int($attribute))
            $this->{$attributeName} = $attribute;
    }
    
    public function getUser()
    {
        return User::model()->getById($this->user_id);
    }
    
    public function getItemType()
    {
        $itemType = ItemType::model()->getById($this->item_type_id);
        if($itemType instanceof ItemType)
            return $itemType;
        
        return false;
    }
    
    public function getItemTypeOptions()
    {
        $options = array();
        $items = ItemType::model()->getAll();
        if( ! empty($items))
        {
            foreach($items as $item)
            {
                if($item instanceof ItemType)
                    $options = array_merge($options, array($item->getId()=>$item->getName()));
            }
        }
        
        
        return $options;
    }
    
    static public function getStatusOptions()
    {
        return array(
            self::STATUS_APPROVE => '已审批',
            self::STATUS_PENDING => '申请中',
        );
    }
    
    public function getDisplayStatus()
    {
        return self::getStatusOptions()[$this->status];
    }

    public function getStatus($isChinese=false)
    {
        if($isChinese)
        {
            if(array_key_exists($this->status, self::getStatusOptions()))
                return  self::getStatusOptions()[$this->status];
        }
        
        return $this->status;
    }
    
    /**
     * 
     * @param type $userId
     * @param type $year
     * @param type $month
     * @return type
     */
    public function getAllByUserMonth($userId, $year, $month, $isUseCursor=true)
    {
        $days = CommonHelper::getDaysByDate($year, $month);
        $str = $year.'-'.$month.'-';
        $startDate = (string)$str.'1';
        $endDate = (string)$str.$days;
        $starTime = strtotime($startDate);
        $endTime = strtotime($endDate);
        $criteria = new EMongoCriteria;
        $criteria->setUseCursor($isUseCursor);
        $criteria->setConditions(array(
            'ctime'=> array('$gte'=> $starTime, '$lte'=> $endTime),
            'user_id'=>$userId,
//            'sort'=>array(
//                'ctime'=>EMongoCriteria::SORT_DESC,
//                '_id'=>EMongoCriteria::SORT_DESC,
//            ),
//            'user_id'=> array('=='=> User::model()->getUserId()),
//            'status'=> array('=='=> Attendance::STATUS_APPROVE)
        ));
        
        return Attendance::model()->findAll($criteria);
    }
}
